<template>
  <div class="home">
    <!-- 辰欣 -->
    <div style="text-align:center">
     <img alt="jkbsoft" :src="this.imgsrc" style="width:40vw;padding-bottom:8vh;">
    </div>
    <!-- 双鲸药业 -->
<!--   <img alt="jkbsoft" src="../../src/assets/sjyy.svg" style="width:90vw;padding-bottom:8vh;">-->
    <!-- 青春宝-->
<!--    <img alt="jkbsoft" src="../../src/assets/bhead_logo.png" style="width:90vw;padding-bottom:8vh;">-->
      <van-overlay :show="show" @click="show = false">
        <div class="wrapper" @click.stop>
          <div class="block">
           登录中...
          </div>
        </div>
      </van-overlay>
    <Login  />
  </div>
</template>

<script>
// @ is an alias to /src
import Vue from 'vue'
import Login from '@/components/Login.vue'
import * as dd from 'dingtalk-jsapi'
import qs from 'qs'
import { Toast, Overlay } from 'vant'
Vue.use(Overlay)
export default {
  name: 'home',
  data () {
    return {
      project: 'default/',
      imgsrc: '',
      // 第一次登陆
      dduserid: this.$route.params.dduserid,
      ykjuserid: this.$route.params.ykjuserid,
      show: false

    }
  },
  created () {
    // alert('created')
    // 为了Login 页面获取
    if (this.dduserid) {
      window.localStorage.setItem('dduserid', this.dduserid)
    }
    const projectData = require('../project.json')
    //console.log(projectData)
    if (projectData.project) {
      this.project = projectData.project
    }
    this.imgsrc = projectData[this.project].imgsrc
    //console.log('imgsrc:' + this.imgsrc)
    if (this.imgsrc) {
      this.imgsrc = require('../../src/assets/' + this.imgsrc)
    } else {
      this.imgsrc = require('../../src/assets/' + projectData['default/'].imgsrc)
    }

    let ua = window.navigator.userAgent.toLowerCase()
    // //console.log(ua)
    // alert('ua:' + ua)
    let logintype = 'wechat'
    // let tourl = window.location.href
    // alert('url1111:' + tourl)

    var r = window.location.search.substr(1).match(new RegExp('(^|&)corpId=([^&]*)(&|$)'))
    if (r != null) {
      this.corpId = unescape(r[2])
    }

    // alert('corpId:' + this.corpId)

    var w = window.location.search.substr(1).match(new RegExp('(^|&)wxuserid=([^&]*)(&|$)'))

    if (w != null) {
      this.wxuserid = unescape(w[2])
    }

    var gz = window.location.search.substr(1).match(new RegExp('(^|&)wxgzuserid=([^&]*)(&|$)'))
    if (gz != null) {
      this.wxgzuserid = unescape(gz[2])
    }

    // let clttype = 'android'

    if (ua.indexOf('wxwork') !== -1) {
      logintype = 'wxwork'
    } else if (ua.indexOf('dingtalk') !== -1) {
      logintype = 'dingding'
    } else if (ua.indexOf('micromessenger') !== -1) {
      logintype = 'wechat'
    } else if (ua.indexOf('tenantid') !== -1) {
      // 友空间
      logintype = 'ykj'
    } else {
      logintype = 'browser'
    }

    // console('logintype:' + logintype)

    if (logintype === 'dingding') {
    this.show = true
    let that = this
    setTimeout(() => { that.show = false }, 2000)
      if (this.corpId) {
        // 说明需要回调
         // alert(this.corpId)
        // Toast(this.corpId)
        // Toast('准备调用dd的code')
        dd.ready(() => {
          // Toast('dd ready')
          dd.runtime.permission.requestAuthCode({
            corpId: this.corpId, // 企业id
            onSuccess: (info) => {
              this.code = info.code
              // Toast('code:' + this.code)

              // 通过该免登授权码可以获取用户身份
              let data = {
                'code': info.code,
                'source': 'dingtalk',
                // 调用新版的dingding api
                'initiatorFromApp': 'true',
                'corpId': this.corpId
              }
              // 准备发回调
              this.axios({
                method: 'post',
                url: '/api/ssoaly',
                data: qs.stringify(data)
              }).then(res => {
                // alert(JSON.stringify(res))
                let dduserid = res.data.dduserid
                let firstlogin = res.data.firstlogin
                let corpId = res.data.corpid
                let ddmsg = res.data.ddmsg

                if (firstlogin === 'true') {
                  // this.$router.push({
                  //   name: 'home',
                  //   params: {
                  //     'dduserid': dduserid
                  //   }
                  // })
                  if (ddmsg === 'true') {
                    Toast('自动登录失败，请输入账号和密码登录')
                  }
                  window.localStorage.setItem('dduserid', dduserid)
                } else if (firstlogin === 'false') {
                  this.$router.push({
                    name: 'main',
                    params: { corpId: corpId }
                  })
                } else {
                  Toast('系统异常 请联系管理员')
                }
              }).catch(res => {
                this.reserror(res)
              })
            },
            onFail: (res) => {
              alert(JSON.stringify(res))
            }

          })
        })
      } else {
        // 钉钉消息
        // var urlparam = window.location.search.substr(1).match(new RegExp('(^|&)urlparm=([^&]*)(&|$)'))
        // alert('urlparam:' + window.location.href)

        let url = window.location.href

        url = url.substr(url.indexOf('urlparam=') + 9)
        let questionmarkIndex = url.indexOf('%3F')
        let pageName = url.substr(url.indexOf('%2F') + 3, questionmarkIndex - 3)
        //console.log('pageName=' + pageName)

        url = url.substr(questionmarkIndex)
        url = url.replace('%3F', '?')
        url = url.replace('%3D', '=')

        // alert('page=' + page +  ",url=" + url)
        const str = url.substr(url.indexOf('?') + 1)
        // arr每个元素都是完整的参数键值
        const arr = str.split('&')
        // result为存储参数键值的集合
        const result = {}
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i].split('=')
          result[item[0]] = item[1]
        }
        this.$router.push({ name: pageName, query: result })
      }
    } else if (logintype === 'ykj') {
      // alert('search:' + window.location.search.substr(1))
      let code = ''
      let w = window.location.search.substr(1).match(new RegExp('(^|&)code=([^&]*)(&|$)'))
      if (w != null) {
        code = unescape(w[2])
      }
      // console('code:' + code)
      let data = {
        'code': code,
        'source': 'ykj',
        // 类似调用新版的dingding api
        'initiatorFromApp': 'true'
      }
            this.axios({
                method: 'post',
                url: '/api/ssoaly',
                data: qs.stringify(data)
              }).then(res => {
                // alert(JSON.stringify(res))
                let ykjuserid = res.data.ykjuserid
                let firstlogin = res.data.firstlogin

                if (firstlogin === 'true') {
                  // this.$router.push({
                  //   name: 'home',
                  //   params: {
                  //     'dduserid': dduserid
                  //   }
                  // })
                  window.localStorage.setItem('ykjuserid', ykjuserid)
                } else if (firstlogin === 'false') {
                  this.$router.push({
                    name: 'main'
                  })
                } else {
                  Toast('系统异常 请联系管理员')
                }
              }).catch(res => {
                this.reserror(res)
              })
    }
  },
  mounted(){
    const pname = this.$route.query.pname
    if(pname==='zcywpt'){
      this.imgsrc = require('../../src/assets/zcywpt_logo.png')
      document.title = '直采运维平台'
    }
  },
  components: {
    Login
  }
}
</script>

<style>
  .home {
    padding-top: 8vh;
    padding-left: 5vw;
    padding-right: 5vw;
  }
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    width:100%;
  }

  .block {
    display: flex;
    border-radius: 1vh;
    width: 65%;
    height: 7vh;
    background-color: #fff;
    font-size: large;
    justify-content: center;
    align-items: center;
  }

</style>
